package com.app.aop;

import com.app.aop.has.HasRedissonLock;
import com.app.exception.BusinessException;
import com.app.framework.utils.TokenUtils;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 分布式锁
 */
@Aspect
@Component
public class RedissonLock {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 定义一个切点（通过注解）
     */
    @Pointcut("@annotation(com.app.aop.has.HasRedissonLock)")
    public void HasRedissonLock() {
    }

    /**
     * Aop切面方法
     *
     * @param joinPoint 切点
     */
    @Around("HasRedissonLock()")
    public Object interceptorDo(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取登录用户ID
        Long loginUserId = TokenUtils.getRequestUserId();
        //Method
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        HasRedissonLock hasRedissonLock = method.getDeclaredAnnotation(HasRedissonLock.class);
        //获取锁的Key
        String lockKey = hasRedissonLock.value() + ":" + loginUserId;
        //获取锁的过期时间
        long leaseTime = hasRedissonLock.leaseTime();
        //获取分布式锁对象
        RLock lock = redissonClient.getLock(lockKey);
        //尝试获取锁
        try {
            boolean isLocked = lock.tryLock(leaseTime, TimeUnit.SECONDS);
            if (!isLocked) {
                throw new BusinessException("请勿重复请求");
            }
            //执行目标方法
            return joinPoint.proceed();
        } finally {
            //释放锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

}